package cn.pzaily.fealetter.aspect;

import cn.pzaily.fealetter.entity.base.BaseEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @PackageName: cn.pzaily.fealatter.aspect
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-19 12:39
 */
@Component
@Aspect
public class DefaultParamsAspect {

    @Before("@annotation(cn.pzaily.fealetter.annotaion.DefaultParams)")
    public void beforeEvent(JoinPoint joinPoint) {

        Long userId = 0L;

        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            Class<?> aClass = arg.getClass();
            if (arg instanceof BaseEntity) {
                Method getIdMethod = getMethod(aClass, "getId");
                if (null != getIdMethod) {
                    try {
                        Object id = getIdMethod.invoke(arg);
                        if (null == id) {
                            Method setCreateUser = getMethod(aClass, "setCreateUser", String.class);
                            if (null != setCreateUser) {
                                setCreateUser.invoke(arg, userId.toString());
                            }
                            Method setCreateTime = getMethod(aClass, "setCreateTime", LocalDateTime.class);
                            if (null != setCreateTime) {
                                setCreateTime.invoke(arg, LocalDateTime.now());
                            }
                        }

                        Method setUpdateUser = getMethod(aClass, "setUpdateUser", String.class);
                        if (null != setUpdateUser) {
                            setUpdateUser.invoke(arg, userId.toString());
                        }

                        Method setUpdateTime = getMethod(aClass, "setUpdateTime", LocalDateTime.class);
                        if (null != setUpdateTime) {
                            setUpdateTime.invoke(arg, LocalDateTime.now());
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }



                }
            }
        }
    }

    private Method getMethod(Class cla, String name, Class... args) {
        try {
            return cla.getMethod(name, args);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }

}
